﻿using System.Collections.Generic;
using DSFramework;
using UnityEngine;
using UnityEngine.AI;

public abstract class ICharacter
{
    protected ICharacterAttr mAttr;
    protected GameObject mGameObject;
    protected NavMeshAgent mNavMeshAgent;
    protected AudioSource mAudioSource;
    protected Animation mAnimation;
    protected IWeapon mWeapon = null;

    public IWeapon Weapon
    {
        get => mWeapon;
        set
        {
            mWeapon = value;
            mWeapon.Owner = this;
            GameObject child = mGameObject.FindChild("weapon-point");
            UnityTool.Attack(child, Weapon.GameObject);
        }
    }

    public Vector3 Position
    {
        get
        {
            if (mGameObject == null)
            {
                Debug.LogError("角色为空!");
                return Vector3.zero;
            }

            return mGameObject.Pos();
        }
    }

    public float AtkRange => mWeapon.AtkRange;

    public ICharacterAttr Attr
    {
        set => mAttr = value;
    }

    public GameObject GameObject
    {
        set
        {
            mGameObject = value;
            mNavMeshAgent = mGameObject.GetOrAddCmpt<NavMeshAgent>();
            mAudioSource = mGameObject.GetOrAddCmpt<AudioSource>();
            mAnimation = mGameObject.GetComponentInChildren<Animation>();
        }
    }

    public void Update()
    {
        mWeapon.Update();
    }

    public abstract void UpdateFSMAI(List<ICharacter> targets);

    public void Attack(ICharacter target)
    {
        mWeapon?.Fire(target.Position);
        mGameObject.LookAt(target.Position);
        PlayAnimation("attack");
        target.UnderAttack(mWeapon.Atk + mAttr.CritValue);
    }

    public virtual void UnderAttack(int damage)
    {
        mAttr.TakeDamage(damage);
    }

    public void Killed()
    {
        //TODO
    }

    protected void DoPlayEffect(string effectName)
    {
        //第一步加载特效 TODO
        GameObject effectGameObject = FactoryManager.AssetFactory.LoadEffect(effectName);
        effectGameObject.Pos(Position);
        //控制销毁 TODO
        effectGameObject.GetOrAddCmpt<DestoryForTime>();
    }

    protected void DoPlaySound(string soundName)
    {
        AudioClip clip = FactoryManager.AssetFactory.LoadAudioClip(soundName); //TODO
        mAudioSource.clip = clip;
        mAudioSource.Play();
    }


    public void PlayAnimation(string animationName)
    {
        mAnimation.CrossFade(animationName);
    }

    public void MoveTo(Vector3 targetPos)
    {
        mNavMeshAgent.SetDestination(targetPos);
        PlayAnimation("move");
    }
}